using B.S.Database.Interface;
using B.S.Database.Interface.Impment;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using B.S.Database.Write.Api.SysConfig;
using System.Reflection;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

// 数据库上下文
builder.Services.AddDbContext<DataDbcontext>(c => c.UseSqlServer(builder.Configuration.GetConnectionString("db")));
// 中介者模式
builder.Services.AddMediatR(c => c.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
// 仓储模式
builder.Services.AddScoped(typeof(IBaseResotity<>), typeof(BaseResotity<>));
// 自动映射
builder.Services.AddAutoMapper(typeof(Mapprofile));

// 添加七牛云配置
builder.Services.Configure<QiNiuConfig>(builder.Configuration.GetSection("qiniuyunOSS"));

// 添加配置服务
builder.Services.AddSingleton<IConfiguration>(builder.Configuration);

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

// JWT认证配置
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o =>
{
    // 密钥
    var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
    o.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
    {
        // 验证签发者
        ValidateIssuer = true,
        // 签发者信息
        ValidIssuer = "BeiJingBW",

        // 验证接收者
        ValidateAudience = true,
        // 接收者信息
        ValidAudience = "BeiJingBW",

        // 验证是否过期
        ValidateLifetime = true,

        // 验证签名密钥
        IssuerSigningKey = new SymmetricSecurityKey(secretByte)

    };
});

// 配置Swagger
builder.Services.AddSwaggerGen(c =>
{
    // 添加XML注释
    var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
    if (File.Exists(xmlPath))
    {
        c.IncludeXmlComments(xmlPath, true);
    }
    
    // 添加JWT认证配置
    c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
    {
        Description = "JWT授权Token Bearer Token值",
        Name = "Authorization",
        In = ParameterLocation.Header,
        Type = SecuritySchemeType.ApiKey,
        BearerFormat = "JWT",
        Scheme = "Bearer"
    });
    
    c.AddSecurityRequirement(new OpenApiSecurityRequirement
    {
        {
            new OpenApiSecurityScheme
            {
                Reference = new OpenApiReference
                {
                    Type = ReferenceType.SecurityScheme,
                    Id = "Bearer"
                }
            },
            new string[] {}
        }
    });
});


var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c =>
    {
        c.SwaggerEndpoint("/swagger/v1/swagger.json", "B.S.Database.Write.Api v1");
        c.RoutePrefix = "swagger";
    });
}

// 配置CORS
app.UseCors(c => c
    .AllowAnyHeader()
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .WithExposedHeaders("Content-Disposition"));

// 暂时禁用HTTPS重定向以解决CORS问题
// app.UseHttpsRedirection();

// þ̬ļ
app.UseStaticFiles();

// Ȩ
app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();
